package controllers

import (
	"WDserver/config"
	"WDserver/util"
	"net"
	"strings"
	"time"
)



func ServcerRun () {
	Saddr := GetPulicIP() + ":" + config.Config().ServerPort
	//fmt.Println(Saddr)
	Listen, err := net.Listen("tcp", Saddr)
	util.CheckError(err)
	defer Listen.Close()
	util.Log("正在监听客户端 ...")
	//等待客户端访问

	for {
		conn, err := Listen.Accept() //监听接收
		if err != nil {
			continue //如果发生错误，继续下一个循环。
		}
		conn.SetReadDeadline(time.Now().Add(time.Duration(5) * time.Second))
		//util.Log(conn.RemoteAddr().String(), "连接成功！") //tcp连接成功
		go handleConnection(conn)

	}
}

func GetPulicIP() string {
	conn, _ := net.Dial("udp", "8.8.8.8:80")
	defer conn.Close()
	localAddr := conn.LocalAddr().String()
	idx := strings.LastIndex(localAddr, ":")
	return localAddr[0:idx]
}